from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource,reqparse,marshal
from models.users import *
from models.channel import *

from models_fields.user_f import *
from utils.login_utils import login_required


channel_bp = Blueprint('channel_bp',__name__,url_prefix='/channels')
api = Api(channel_bp)



# 所有频道信息
class Channels(Resource):
    def get(self):
        channel = Channel.query.all()
        channel_f = marshal(channel,channel_fields)
        print('获取频道数据',channel_f)
        return jsonify(code=200,msg='获取所有注频道成功',data=channel_f)


# 频道的文章
class ChannelsNews(Resource):
    @login_required
    def get(self):
        pares = reqparse.RequestParser()
        pares.add_argument('cid')
        args = pares.parse_args()
        print('想要获取文章的频道id',args.get('cid'))
        try:
            newss = News.query.filter_by(channel_id=args.get('cid')).all()
            list1=[]
            for news in newss:
                user = User.query.filter_by(uid=news.user_id).first()
                news_f = marshal(news,news_fields)
                user_f = marshal(user,user_fields)
                news_f['user']=user_f
                list1.append(news_f)
            print(list1)
            return jsonify(code=200, msg='获取所有频道的文章成功', data=list1)
        except Exception as e:
            print('AAAA','获取频道的所有文章及文章用户错误',e)
            return jsonify(code=204,msg='查询错误')

# 文章的详情
# class NewsInfo(Resource):
#     def get(self,id):
#         News.query.filter_by(nid=id).first()




class CollectionResource(Resource):
    # @login_required
    def get(self,nid):
        user_id = 1
        rest = Collection.query.filter_by(user_id=user_id,news_id = nid).is_delete
        print(rest)
        pass
        # if rest:
        #     Collection.query.filter_by(user_id=user_id,news_id=nid).update({'is_delete':True})
        #     db.session.commit()
        #     return jsonify(msg='收藏成功',code=200)
        # else:
        #     Collection.query.filter_by(user_id=user_id,news_id=nid).update({'is_delete': False})
        #     db.session.commit()
        #     return jsonify(msg='取消收藏成功',code=200)











api.add_resource(CollectionResource,'/starts/<int:nid>')
api.add_resource(Channels,'/category')   #获取所有频道
api.add_resource(ChannelsNews,'/news')   #获取频道的所有文章





